<?php
namespace SimpleMVC\lib;

class Router {
	
	private $urlSuffix;
	private $urlRules;
	
	public function __construct($urlSuffix, array $urlRules)
	{
		$this->urlSuffix = $urlSuffix;
		$this->urlRules = $urlRules;
	}
	
	private function getUri()
	{
		if (!isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) {
			return '';
		}
		
		$uri = $_SERVER['REQUEST_URI'];
		if (($pos = strpos($uri, '?')) !== false) {
			$uri = substr($uri, 0, $pos);
		}
		if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) {
			$uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
		}
		$uri = trim($uri, '/');
		
		$urlSuffix = strtolower($this->urlSuffix);
		if ($urlSuffix != '')
		{
			if (strpos($urlSuffix, '.') !== 0) {
				$urlSuffix = '.' . $urlSuffix;
			}
			$len = strlen($urlSuffix);
			if (strtolower(substr($uri, -$len)) === $urlSuffix) {
				$uri = substr($uri, 0, -$len);
			}
		}
		
		return $uri;
	}
	
	public function getPossibleRoutes()
	{
		$uri = $this->getUri();
		
		$routes = array();
		foreach ($this->urlRules as $rule)
		{
			if (preg_match($rule['pattern'], $uri, $matches) == 1)
			{
				$route = array();
				$route['class'] = $rule['class'];
				$route['method'] = $rule['method'];
				$routes[] = $route;
				foreach ($matches as $i => $match)
				{
					if ($i == 0) {
						continue;
					}
					if (isset($rule['params'][$i]))
					{
						$_GET[$rule['params'][$i]] = $match;
						$_REQUEST[$rule['params'][$i]] = $match;
					}
				}
				return $routes;;
			}
		}
		
		$parts = explode('/', $uri);
		$parts = array_values(array_filter($parts));
		foreach ($parts as $i => $part) {
			$parts[$i] = strtolower($part);
		}
		
		$count = count($parts);
		if ($count < 2)
		{
			$route = array();
			$route['class'] = '\\controller\\' . ($count == 0 ? 'Index' : $this->toHump($parts[0]));
			$route['method'] = 'action' . ($count == 2 ? $this->toHump($parts[1]) : 'Index');
			$routes[] = $route;
		}
		else
		{
			$className = '\\controller';
			for ($i = 0; $i < $count - 1; ++$i)
			{
				if ($i < $count - 2) {
					$className .= '\\' . $parts[$i];
				} else {
					$className .= '\\' . $this->toHump($parts[$i]);
				}
			}
			$route = array();
			$route['class'] = $className;
			$route['method'] = 'action' . $this->toHump($parts[$count - 1]);
			$routes[] = $route;
			
			$className = '\\controller';
			for ($i = 0; $i < $count; ++$i)
			{
				if ($i < $count - 1) {
					$className .= '\\' . $parts[$i];
				} else {
					$className .= '\\' . $this->toHump($parts[$i]);
				}
			}
			$route = array();
			$route['class'] = $className;
			$route['method'] = 'actionIndex';
			$routes[] = $route;
		}
		
		return $routes;
	}
	
	private function toHump($str)
	{
		return preg_replace_callback('/\-([a-z])/', function($matches) {
			return strtoupper($matches[1]);
		}, ucfirst($str));
	}
	
}
